package ro.ubbcluj.cs.damate.services;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import ro.ubbcluj.cs.damate.persistence.entities.Event;
import ro.ubbcluj.cs.damate.persistence.entities.EventParameter;
import ro.ubbcluj.cs.damate.persistence.entities.EventType;
import ro.ubbcluj.cs.damate.persistence.entities.File;
import ro.ubbcluj.cs.damate.persistence.repository.EventParameterRepository;
import ro.ubbcluj.cs.damate.persistence.repository.EventRepository;
import ro.ubbcluj.cs.damate.persistence.repository.EventTypeRepository;
import ro.ubbcluj.cs.damate.utils.PluginEventConstants;

import java.util.List;

/**
 * @author Lóránd Fazakas (lfazakas)
 *         Date: 2013.06.28.
 *         Time: 15:02
 */
@Service
public class EventService {

    @Autowired
    private EventRepository eventRepository;

    @Autowired
    private EventTypeRepository eventTypeRepository;

    @Autowired
    private EventParameterRepository eventParameterRepository;

    @Transactional
    public void create(Event transientEvent) {
        eventRepository.save(transientEvent);
    }

    @Transactional
    public void delete(Event persistentEvent) {
        eventRepository.delete(persistentEvent);
    }

    @Transactional
    public void createEventParameter(EventParameter transientEventParameter) {
        eventParameterRepository.save(transientEventParameter);
    }

    @Transactional
    public void deleteEventParameter(EventParameter persistentEventParameter) {
        eventParameterRepository.delete(persistentEventParameter);
    }

    public EventType findEventTypeByCode(int code) {
        List<EventType> types = eventTypeRepository.findByCode(code);
        if (types != null && !types.isEmpty()) {
            return types.get(0);
        } else {
            EventType type = new EventType();
            type.setCode(code);
            type.setName(PluginEventConstants.getEventName(code));
            return type;
        }
    }

    public List<Event> findEventByFiles(List<File> files) {
        return eventRepository.findByResourceFiles(files);
    }
}
